package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.ArticleCommentLikeDao;
import com.jbp.model.Article;
import com.jbp.model.ArticleComment;
import com.jbp.model.ArticleCommentLike;
import com.jbp.model.ArticleLike;
import com.jbp.service.ArticleCommentLikeService;
import com.jbp.service.ArticleCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 评论的点赞(ArticleCommentLike)表服务实现类
 * @author cc
 * @since 2020-08-25 14:37:34
 */
@Service
public class ArticleCommentLikeServiceImpl extends ServiceImpl<ArticleCommentLikeDao, ArticleCommentLike> implements ArticleCommentLikeService {
    @Autowired
    private ArticleCommentService articleCommentService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<ArticleCommentLike> queryWrapper = new QueryWrapper<>();
        if (params.get("id") != null){
            queryWrapper.like("id",params.get("id"));
        }
        IPage<ArticleCommentLike> page = this.page(
                new Query<ArticleCommentLike>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void like(ArticleCommentLike req) {
        ArticleComment articleComment = articleCommentService.getById(req.getCommentId());

        ArticleCommentLike articleCommentLike = getOne(new QueryWrapper<ArticleCommentLike>()
                .eq("comment_id", req.getCommentId())
                .eq("reader_id", req.getReaderId())
        );
        int like = 0;
        if (articleCommentLike!=null) {
            if (!articleCommentLike.getStatus().equals(req.getStatus())) {
                like = req.getStatus() == 0 ? -1 : 1;
                articleCommentLike.setStatus(req.getStatus());
                updateById(articleCommentLike);
            }
        } else {
            like = req.getStatus() == 0 ? 0 : 1;
            save(req);
        }

        if (like!=0) {
            articleComment.setLikeCount(articleComment.getLikeCount()+like);
            articleCommentService.updateById(articleComment);
        }
    }
}